package edu.nf.vac.api.controller;


import edu.nf.vac.api.vo.ResultVO;
import edu.nf.vac.auth.inf.UserAuthService;
import edu.nf.vac.auth.inf.UserTokenService;
import edu.nf.vac.users.dto.UserDTO;
import edu.nf.vac.users.inf.UserService;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @author LQJ
 * @date 2022/3/30
 */
@Api(tags = "用户服务接口")
@RestController
@RequestMapping("/api/v1")
public class UserController extends BaseController {

    @DubboReference(interfaceClass = UserAuthService.class,
            version="1.0.0",check = false)
    private UserAuthService authService;

    @DubboReference(interfaceClass = UserTokenService.class,
            version="1.0.0",check = false)
    private UserTokenService tokenService;

    @DubboReference(interfaceClass = UserService.class,
            version="1.0.0",check = false)
    private UserService userService;

    /**
     * 用户登陆
     * @param account
     * @param password
     * @return
     */
    @PostMapping("/user/login")
    @ApiOperation(value="用户登陆", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name="account", value="用户的手机号", required=true, dataTypeClass=String.class, paramType="query"),
            @ApiImplicitParam(name="password", value="密码", required=true, dataTypeClass=String.class, paramType="query")
    })
    @ApiResponses({
            @ApiResponse(code = 200, message = "登陆成功，服务端返回jwt", response = ResultVO.class),
            @ApiResponse(code = 401, message = "认证失败"),
            @ApiResponse(code = 500, message = "服务异常")
    })
    public ResultVO<String> login(String account, String password, HttpServletResponse response) {
        UserDTO userDTO = authService.authenticate(account, password);
        Map<String, Object> payload = new HashMap();
        payload.put("uid", userDTO.getUid());
        //token过期时间为1个月
        String token = tokenService.create(payload, 2629800000L);
        response.setHeader("token", token);
        return success();
    }

    /**
     * 获取个人信息
     * @return
     */
    @GetMapping("/user/personal")
    @ApiOperation(value="个人信息", httpMethod = "GET")
    @ApiResponses({
            @ApiResponse(code = 200, message = "返回用户信息", response = ResultVO.class),
            @ApiResponse(code = 401, message = "认证失败"),
            @ApiResponse(code = 500, message = "服务异常")
    })
    public ResultVO<UserDTO> getUserInfo(@RequestAttribute("uid") Integer uid) {
        UserDTO userDTO = userService.getUserById(uid);
        return success(userDTO);
    }
}
